package com.roy.sms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.roy.sms.dao.ArticleDao;
import com.roy.sms.dao.ColumnDao;
import com.roy.sms.model.Article;
import com.roy.sms.model.Column;
import com.roy.sms.util.Pager;
import com.roy.sms.util.StringUtil;
import com.roy.sms.vo.ArticleVO;
import com.roy.sms.vo.ColumnVO;

@Service
public class ArticleService {

	@Resource
	private ArticleDao articleDao;
	
	@Resource
	private ColumnDao columnDao;
	
	@Transactional
	public void add(ArticleVO articleVO){
		Article article = articleVO.getArticle();
		article.setCreateDate(new Date());
		article.setColumn(columnDao.load(articleVO.getColumnId()));
		articleDao.add(article);
	}
	
	@Transactional
	public void update(ArticleVO articleVO){
		Column column = columnDao.load(articleVO.getColumnId());
		Article article = articleVO.getArticle();
		article.setColumn(column);
		articleDao.update(article);
	}
	
	@Transactional
	public void delete(String ids){
		if (!StringUtil.isEmpty(ids)) {
			String[] sid = ids.split(",");
			for (String id : sid) {
				articleDao.delete(Integer.valueOf(id));
			}
		}
	}
	
	@Transactional
	public Pager<ArticleVO> list(int rowBeginIndex , int rowCount, ColumnVO columnVO){
		List<Article> articles = null;
		int count = 0;
		if(columnVO == null){
		articles = articleDao.list(rowBeginIndex, rowCount);
		count = articleDao.getTotal();
		} else {
			Column c = columnVO.getColumn();
			articles = articleDao.list(c, rowBeginIndex, rowCount);
			count = articleDao.getTotal(c);
		}
		
		Pager<ArticleVO> page = new Pager<ArticleVO>();
		page.setTotal(count);
		List<ArticleVO> articleVOs = new ArrayList<ArticleVO>();
		for(Article article : articles){
			articleVOs.add(new ArticleVO(article));
		}
		
		page.setRows(articleVOs);
		return page;
	}
	
	@Transactional
	public void publish(int state, String ids){
		if (!StringUtil.isEmpty(ids)) {
			String[] sid = ids.split(",");
			for (String id : sid) {
				articleDao.updateState(state, Integer.valueOf(id));
			}
		}
	}
	
	@Transactional
	public ArticleVO loadArticle(int id){
		return new ArticleVO(articleDao.load(id));
	}
	
}
